<!DOCTYPE html>
<html>

<head>
    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
	<meta http-equiv="Access-Control-Allow-Origin" content="*">
    <title>flv.js demo</title>
    <link rel="stylesheet" type="text/css" href="demo.css" />
</head>

<body>
    
    <div class="mainContainer">
        <div>
            <div id="streamURL">
			<br/>
                <div class="url-input">
                    <label for="ip">设备推流地址:</label>
                    <input id="ip" type="text" value="localhost" onchange="saveSettings()"/>

                    <label for="tcpPort">&nbsp;推流端口:</label>
                    <input id="tcpPort" type="text" value="6037" onchange="saveSettings()"/>

					<label for="deviceSn">&nbsp;上线卡号:</label>
                    <input id="deviceSn" type="text" value="013609616322" onchange="saveSettings()"/>

                    <label for="channelId">&nbsp;视频通道:</label>
                    <select name="channelId" id="channelId" onchange="saveSettings()">
					  <option value="1">通道1</option>
					  <option value="2">通道2</option>
					  <option value="3">通道3</option>
					  <option value="4">通道4</option>
					  <option value="5">通道5</option>
					  <option value="6">通道6</option>
					  <option value="7">通道7</option>
					  <option value="8">通道8</option>
					</select>
                </div><br/>

				<div class="url-input">
                    <label for="streamUrl">前端拉流地址:</label>
                    <input id="streamUrl" type="text" value="http://localhost:26080/live/013609616322-1-live.flv" />
                </div><br/>

				<div class="url-input">
                    <label for="api">指令下发接口:</label>
                    <input id="api" type="text" value="http://localhost:8080/command/013609616322/9101.json" />
                    <button onclick="startLive()">开启视频</button>
					<button onclick="stopLive()">停止视频</button>
                </div>

                <div class="options">
                    <input type="checkbox" id="isLive" onchange="saveSettings()" />
                    <label for="isLive">isLive</label>
                    <input type="checkbox" id="withCredentials" onchange="saveSettings()" />
                    <label for="withCredentials">withCredentials</label>
                    <input type="checkbox" id="hasAudio" onchange="saveSettings()" checked />
                    <label for="hasAudio">hasAudio</label>
                    <input type="checkbox" id="hasVideo" onchange="saveSettings()" checked />
                    <label for="hasVideo">hasVideo</label>
                    <input type="checkbox" id="enableStashBuffer" onchange="saveSettings()" checked />
                    <label for="enableStashBuffer">enable stash</label>
                </div>
            </div>
        </div>
        <div class="video-container">
            <div>
                <video name="videoElement" class="centeredVideo" controls autoplay>
                    Your browser is too old which doesn't support HTML5 video.
                </video>
                <audio name="audioElement">222</audio>
            </div>
        </div>
        <div class="controls">
            <button onclick="flv_load()">Load</button>
            <button onclick="flv_start()">Start</button>
            <button onclick="flv_pause()">Pause</button>
            <button onclick="flv_destroy()">Destroy</button>
            <input style="width:100px" type="text" name="seekpoint"/>
            <button onclick="flv_seekto()">SeekTo</button>
            <button onclick="enableMute()" type="button">关闭声音</button>
            <button onclick="disableMute()" type="button">打开声音</button>
            <button onclick="exitFullscreen()" type="button">关闭全屏</button>
            <button onclick="FullScreen()" type="button">打开全屏</button>
        </div>
        <textarea name="logcatbox" class="logcatBox" rows="10" readonly></textarea>
    </div>
	<div style="width:100%;text-align:center;margin-top:5px;"><a  href="https://www.legaoyi.com" target="_blank" >广西乐高易网络有限公司 www.legaoyi.com</a></div><br/><br/>

    <script src="flv.min.js"></script>
     <script src="jquery-1.8.1.js"></script>
    
    <script>
        var checkBoxFields = ['isLive', 'withCredentials', 'hasAudio', 'hasVideo', 'enableStashBuffer'];
        var element = document.getElementsByName('videoElement')[0];
        var audioElement = document.getElementsByName('audioElement')[0];
		var _lastLogTime = 0;
		var _onErrorRestart = true;

        //关闭声音
        function enableMute(){
            element.muted=true;
        }
        //打开声音
        function disableMute(){
            element.muted=false;
        }

        //关闭全屏
        function exitFullscreen(){
            if (element.exitFullscreen) {
                element.exitFullscreen();
            } else if (element.mozCancelFullScreen) {
                element.mozCancelFullScreen();
            } else if (element.webkitCancelFullScreen) {
                element.webkitCancelFullScreen();
            }
        }
        //打开全屏
        function FullScreen(){
            if (element.requestFullscreen) {
                element.requestFullscreen();
            } else if (element.mozRequestFullScreen) {
                element.mozRequestFullScreen();
            } else if (element.webkitRequestFullScreen) {
                element.webkitRequestFullScreen();
            }
        }

        function flv_load() {
                console.log('isSupported: ' + flvjs.isSupported());
                var i;
                var mediaDataSource = {
                    type: 'flv'
                };
                for (i = 0; i < checkBoxFields.length; i++) {
                    var field = checkBoxFields[i];
                    /** @type {HTMLInputElement} */
                    var checkbox = document.getElementById(field);
                    mediaDataSource[field] = checkbox.checked;
                }
                mediaDataSource['url'] = document.getElementById('streamUrl').value;
                console.log('MediaDataSource', mediaDataSource);
                flv_load_mds(mediaDataSource);
                // player.play();
                setTimeout(function() { player.play(); }, 100);
        }

        function flv_load_mds(mediaDataSource) {
            element.controls=true;
            if (typeof player !== "undefined") {
                if (player != null) {
                    player.unload();
                    player.detachMediaElement();
                    player.destroy();
                    player = null;
                }
            }
            // 创建flV播放器
            player = flvjs.createPlayer(mediaDataSource, {
                enableWorker: false,
                lazyLoadMaxDuration: 3 * 60, // 延迟负载最大持续时间180s
                seekType: 'range',  //滑块控件range
            });
            console.log('flv播放器创建成功');
            player.attachMediaElement(element);
            player.load();

			addEventListener();
        }

        function flv_start() {
            player.play();

			addEventListener();
        }

        function flv_pause() {
            player.pause();
        }

        function flv_destroy() {
            player.pause();
            player.unload();
            player.detachMediaElement();
            player.destroy();
            player = null;
        }

        function flv_seekto() {
            var input = document.getElementsByName('seekpoint')[0];
            player.currentTime = parseFloat(input.value);
        }

		 function ls_set(key, value) {
            try {
                localStorage.setItem('flvjs_demo.' + key, value);
            } catch (e) {}
        }

        function saveSettings() {
            var i;
            for (i = 0; i < checkBoxFields.length; i++) {
                var field = checkBoxFields[i];
                /** @type {HTMLInputElement} */
                var checkbox = document.getElementById(field);
                ls_set(field, checkbox.checked ? '1' : '0');
            }

			var ip = document.getElementById('ip').value;
            ls_set('ip', ip);

			var tcpPort = document.getElementById('tcpPort').value;
            ls_set('tcpPort', tcpPort);

			var deviceSn = document.getElementById('deviceSn').value;
            ls_set('deviceSn', deviceSn);

			var channelId = document.getElementById('channelId').value;
            ls_set('channelId', channelId);

            var streamUrl = "ws://"+ip+":26080/live/"+deviceSn+"-"+channelId+"-live.flv";
			document.getElementById('streamUrl').value = streamUrl;
            ls_set('streamUrl', streamUrl);

			var api = "http://localhost:8080/command/"+deviceSn+"/9101.json";
			document.getElementById('api').value = api;
            ls_set('api', api);
        }

        function loadSettings() {
            var i;
            for (i = 0; i < checkBoxFields.length; i++) {
                var field = checkBoxFields[i];
                /** @type {HTMLInputElement} */
                var checkbox = document.getElementById(field);
                var c = ls_get(field, checkbox.checked ? '1' : '0');
                checkbox.checked = c === '1' ? true : false;
            }

            var obj = document.getElementById('streamUrl');
            obj.value = ls_get('streamUrl', obj.value);

			obj = document.getElementById('ip');
            obj.value = ls_get('ip', obj.value);

			obj = document.getElementById('tcpPort');
            obj.value = ls_get('tcpPort', obj.value);

			obj = document.getElementById('deviceSn');
            obj.value = ls_get('deviceSn', obj.value);

			obj = document.getElementById('channelId');
            obj.value = ls_get('channelId', obj.value);


			obj = document.getElementById('api');
            obj.value = ls_get('api', obj.value);
        }

        function ls_get(key, def) {
            try {
                var ret = localStorage.getItem('flvjs_demo.' + key);
                if (ret === null) {
                    ret = def;
                }
                return ret;
            } catch (e) {}
            return def;
        }

   
        function showVersion() {
            var version = flvjs.version;
            document.title = document.title + " (v" + version + ")";
        }

        var logcatbox = document.getElementsByName('logcatbox')[0];
        flvjs.LoggingControl.addLogListener(function(type, str) {
            logcatbox.value = logcatbox.value + str + '\n';
            logcatbox.scrollTop = logcatbox.scrollHeight;
        });

        document.addEventListener('DOMContentLoaded', function () {
            showVersion();
            //flv_load();
        });

	function addEventListener(){
    // flvjs.Events
    // ERROR	播放期间由于任何原因发生错误
    // LOADING_COMPLETE	输入MediaDataSource已完全缓冲到结束
    // RECOVERED_EARLY_EOF	缓冲期间发生意外的网络EOF，但已自动恢复
    // MEDIA_INFO	提供媒体的技术信息，例如视频/音频编解码器，比特率等。
    // METADATA_ARRIVED	用“ onMetaData”标记提供FLV文件（流）可以包含的元数据。
    // SCRIPTDATA_ARRIVED	提供FLV文件（流）可以包含的脚本数据（OnCuePoint / OnTextData）。
    // STATISTICS_INFO	提供播放统计信息，例如丢帧，当前速度等。
	// flvjs.Events.MEDIA_HEADER_RESET  扩展flvjs事件，重置flv头事件

    //flvjs.ErrorTypes
    // NETWORK_ERROR	与网络有关的错误
    // MEDIA_ERROR	与媒体有关的错误（格式错误，解码问题等）
    // OTHER_ERROR	任何其他未指定的错误

    //flvjs.ErrorDetails
    // NETWORK_EXCEPTION	与网络其他任何问题有关；包含一个message
    // NETWORK_STATUS_CODE_INVALID	与无效的HTTP状态代码（例如403、404等）相关。
    // NETWORK_TIMEOUT	相关超时请求问题
    // NETWORK_UNRECOVERABLE_EARLY_EOF	与无法恢复的意外网络EOF相关
    // MEDIA_MSE_ERROR	与MediaSource的错误有关，例如解码问题
    // MEDIA_FORMAT_ERROR	与媒体流中的任何无效参数有关
    // MEDIA_FORMAT_UNSUPPORTED	flv.js不支持输入的MediaDataSource格式
    // MEDIA_CODEC_UNSUPPORTED	媒体流包含不支持的视频/音频编解码器
    try {
      player.on(flvjs.Events.ERROR, (errorType, errorDetail, errorInfo) => {
        //错误重连
        const now = Date.now();
        if (now - _lastLogTime > 3 * 1000) {
          if (_onErrorRestart) {
            restart();
          } else if (!_onErrorRestart) {
            alert('音视频直播出错，请稍后重试！')
            stop();
          }
          _lastLogTime = now;
          console.error(errorType, errorDetail, errorInfo);
        }
      })

      player.on(flvjs.Events.RECOVERED_EARLY_EOF, () => {
        //错误重连
        const now = Date.now();
        if (now - _lastLogTime > 3 * 1000) {
          if (_onErrorRestart) {
            restart();
          } else if (_onErrorRestart) {
            alert('音视频直播出错，请稍后重试！')
            stop()
          }
          _lastLogTime = now
          console.error(flvjs.Events.RECOVERED_EARLY_EOF)
        }
      })

      player.on(flvjs.Events.MEDIA_HEADER_RESET, () => {
	     console.log("********restart*********");
         restart();
      });

      //画面卡死重连,有点问题，todo
          /**
           let lastDecodedFrame = 0;
           flvPlayer.on("statistics_info", function (res) {
        if (lastDecodedFrame == 0) {
          lastDecodedFrame = res.decodedFrames
        }else {
          if (lastDecodedFrame != res.decodedFrames) {
            lastDecodedFrame = res.decodedFrames
          } else {
            stopFlvPlayer(flvPlayer)
            setTimeout(function() {
              createFlvPlayer(player, playerId, src, hasVideo, hasAudio, isLive)
              lastDecodedFrame = 0
            }, 100)
          }
        }
      })**/
    }catch(e){
       console.error(e);
    }
  }

  function restart(){
     flv_destroy();

	 setTimeout(function() { flv_load(); }, 100);
  }

  function stop(){
     flv_destroy();
  }


  function startLive(){
      var ip = ls_get("ip");
	  var tcpPort = ls_get("tcpPort");
      var channelId = ls_get("channelId");
	  var api = ls_get("api");
      var data = JSON.stringify({
	     "ip":ip,            
	     "tcpPort":tcpPort,            
	     "udpPort":0,            
	     "channelId":channelId,            
	     "dataType":0,            
	     "streamType":0
	  });
      $.ajax({
            url: api,
            data: data,
            type: "POST",
            dataType: "json",
			contentType:'application/json',
            success: function(data) {
				if(data.code==0){
				   flv_load();
				}else{
				    alert(data.message);
				 }
            },
			error:function(data) {
				alert("调用接口出错！");
			}
        });
   }

    function stopLive(){
      var channelId = ls_get("channelId");
	  var api = ls_get("api");
      var data = JSON.stringify({       
	     "command":0,            
	     "channelId":channelId,            
	     "dataType":0,            
	     "streamType":0
	  });
      $.ajax({
            url: api.replace("9101","9102"),
            data: data,
            type: "POST",
            dataType: "json",
			contentType:'application/json',
            success: function(data) {
				if(data.code==0){
				   flv_destroy();
				}else{
				   alert(data.message);
				}
            },
			error:function(data) {
				alert("调用接口出错！");
			}
        });
   }

    </script>
    
</body>

</html>